<template>
  <scroll-view>
    <div class="wrap">
      <!--  省市区弹窗  -->
      <Drawer ref="siteRef" mask>
        <SiteSelect :value="defSite" @cancel="cancelSite" @value="setSite" />
      </Drawer>
      <!--时间选择弹框-->
      <Drawer ref="DateRef" mask>
        <!-- <div class="date">-->
        <DateSelect title="证件有效期" type="dates" @cancel="cancelDate" @value="DateChange" />
        <!-- </div>-->
      </Drawer>
      <!--  身份证已被使用弹框  -->
      <Popup ref="cardNoRef">
        <Pconfirm cancel-text="我知道了" confirm-text="重新登录" tip-title="提示" @cancel="iKnow" @confirm="logInAgain">
          <template #tip>
            <div class="tips">
              您填写的证件号码已注册,关联账号尾号为{{ CPM_Mobile.slice(-4) }}您可使用此账号直接登录。如账号无法继续使用请联系您的收稻专属客服进行处理!
            </div>
          </template>
        </Pconfirm>
      </Popup>
      <Drawer ref="idTypeRef" mask>
        <StateSelect :config="idTypeEnum" title="请选择证件类型" @cancel="idTypeRef.change()" @value="idTypeConfirmFn" />
      </Drawer>
      <!--企业认证失败tips-->
      <div v-if="formStatus === 3" class="reject_tip flex_start">
        <Icon :styles="{transform: 'rotate(180deg)', margin:'4rpx 12rpx 0 0'}" name="icon-audit_progress_bohui" size="40" />
        {{ `审核已被驳回，${rejectReason}，请修改后重新提交` }}
      </div>
      <!--  表单  -->
      <div :style="{paddingTop: formStatus === 3 ? '110rpx' : '30rpx'}" class="box_info">
        <div class="title">填写基本资料</div>
        <div class="title_1">为了保证账号真实有效，请完成下方资料填写</div>
        <LabelAndValue :box-style="labelValueStyle" colon label="证件类型" label-width="200" required>
          <div class="select" @tap="idTypeRef.change()">
            {{ cardTypeName || '身份证' }}
            <Icon :styles="{opacity: 0.5 }" name="icon-youjiantou" size="30" />
          </div>
        </LabelAndValue>
        <div class="identity">{{ idCardTitle.name }}</div>
        <!--证件人像面 -->
        <div>
          <LabelAndValue :box-style="{paddingLeft: 0, marginTop: '20rpx'}" :label="idCardTitle.idCardFrontTip" label-width="500" required />
          <Image v-if="form.CardImgBack"
                 :name="form.CardImgBack"
                 :styles="{border: '2rpx solid rgba(0, 0, 0, 0.15)', borderRadius: '20rpx', position: 'relative', margin: '20rpx 0 28rpx 80rpx'}"
                 height="300"
                 width="480"
          >
            <Icon
              :styles="{ position: 'absolute', top: '0', right: '0'}"
              name="icon-tupianguanbianniu"
              size="40"
              @tap="form.CardImgBack = ''"
            />
          </Image>
          <Image v-else :name="idCardTitle.cardDefaultPersonImg" :styles="{margin: '20rpx 0 28rpx 80rpx'}" height="300" oss type="png" width="480" @tap="toIDViewFn('IDPersonImg')" />
        </div>
        <!-- 证件正面 身份证国徽面是正面-->
        <div>
          <LabelAndValue :box-style="{paddingLeft: 0}" :label="idCardTitle.idCardBackTip" label-width="500" required />
          <Image
            v-if="form.CardImgFront"
            :name="form.CardImgFront"
            :styles="{border: '2rpx solid rgba(0, 0, 0, 0.15)', borderRadius: '20rpx', position: 'relative', margin: '20rpx 0 0 80rpx'}"
            height="300"
            width="480"
          >
            <Icon
              :styles="{ position: 'absolute', top: '0', right: '0'}"
              name="icon-tupianguanbianniu"
              size="40"
              @tap="form.CardImgFront = ''"
            />
          </Image>
          <Image v-else :name="idCardTitle.cardDefaultImgFront" :styles="{margin: '20rpx 0 0 80rpx'}" height="300" oss type="png" width="480" @tap="toIDViewFn('IDFront')" />
        </div>
        <LabelAndValue :box-style="labelValueStyle" colon label="姓名" label-width="210" required>
          <Input v-model:value="form.Name" :styles="{ color:'rgba(0, 0, 0, 0.25)' }" disabled placeholder="未获取" />
        </LabelAndValue>
        <LabelAndValue :box-style="labelValueStyle" colon label="性别" label-width="210" required>
          <RadioSelect :config="[{label: '男', key: '0', disabled: true}, {label: '女', key: '1', disabled: true}]" :value="form.Sex" height="80" position="left" @value="form.Sex = $event" />
        </LabelAndValue>
        <LabelAndValue :box-style="labelValueStyle" colon label="证件号码" label-width="260" required>
          <Input v-model:value="form.CardNo" :maxlength="idCardTitle.maxLength" :styles="{paddingLeft: 0,color:'rgba(0, 0, 0, 0.25)' }" disabled placeholder="未获取" />
        </LabelAndValue>
        <LabelAndValue :box-style="labelValueStyle" colon label="证件有效期" label-width="260" required>
          <div class="card_no">
            <div :style="{color: 'rgba(0, 0, 0, 0.25)', paddingLeft: 0}" class="_placeholder">{{ cardText }}</div>
            <!-- <div :style="{color: `rgba(0, 0, 0, 0.${form.IsLongterm || form.CardExpdate ? '85' : '25'})`, paddingLeft: 0}" class="_placeholder">{{ cardText }}</div>
            <Icon :styles="{opacity: 0.5 }" name="icon-youjiantou" size="30" /> -->
          </div>
        </LabelAndValue>
        <LabelAndValue v-if="form.CardType === '5001'" :box-style="labelValueStyle" colon label="身份证住址" label-width="260" required>
          <Input v-model:value="form.IDAddress" :styles="{paddingLeft: 0,color: 'rgba(0, 0, 0, 0.25)'}" disabled placeholder="未获取" />
        </LabelAndValue>
        <!-- <div v-if="form.CardType === '5001'" class="card_no_switch">
          <Switch :value="form.IsLongterm" type="round" @value="Swictch" />
          <div class="switch_content">长期有效</div>
        </div> -->
      </div>
      <div class="box_card">
        <div class="identity">其他信息</div>
        <LabelAndValue :box-style="labelValueStyle" :value-style="{paddingLeft: '16rpx'}" colon label="常驻地区" label-width="230" position="left" required>
          <div class="card_no" @tap="selectSite">
            <div style="height: 100%; display: flex; align-items: center;" v-html="siteText" />
            <Icon :styles="{opacity: 0.5 }" name="icon-youjiantou" size="30" />
          </div>
        </LabelAndValue>
        <LabelAndValue :box-style="labelValueStyle" colon label="详细地址" label-width="210" required>
          <Input v-model:value="form.Address" placeholder="请输入常驻地区详细地址" />
        </LabelAndValue>
        <LabelAndValue :box-style="labelValueStyle" colon label="电子邮箱" label-width="210" required>
          <Input v-model:value="form.Email" placeholder="请输入邮箱地址" />
        </LabelAndValue>
        <div class="mt10 flex_start_cen" style="color: rgba(0, 0, 0, 0.45);font-size: 24rpx">
          <Icon :styles="{marginRight:'10rpx'}" name="icon-tishi" size="30" />
          默认手机运营商邮箱或填写您的常用邮箱
        </div>
        <div class="flex_start_cen mt26">
          <div class="touch_area flex_start_cen" @tap="selectFn">
            <div :style="{background: isAllRead ? '#1890FF' : 'transparent', borderColor: isAllRead ? '#1890FF' : '#48484a'}" class="meidao-switch-more">
              <Icon name="icon-dui" size="22" />
            </div>
          </div>
          <div class="read_tip" @tap="cooperateNoticeRef.change()">我已全部阅读并同意<span class="base_color">《合作须知》</span></div>
        </div>
        <Button class="btn" size="L" @confirm="submit">提交</Button>
      </div>
    </div>
  </scroll-view>
  <!--  待审核，被驳回-->
  <Popup
    ref="CheckRef"
  >
    <Confirm
      title="账号被驳回"
      @no="changeCheckShow"
      @ok="changeCheckShow"
    >
      {{ `审核已被驳回，驳回原因：${rejectReason}，请修改后重新提交` }}
    </Confirm>
  </Popup>
  <!-- 合作须知 -->
  <Drawer ref="cooperateNoticeRef">
    <div class="popup_box">
      <div class="popup_title">
        <div style="font-size: 36rpx">合作须知详情</div>
        <div class="icon_close" @tap="closeCooperateNotice">
          <Icon name="icon-shanchu-4" size="28" />
        </div>
      </div>
      <scroll-view :scroll-y="true" lower-threshold="10" style="height: 20vh" @scrolltolower="isAllRead = true">
        <div class="content popup_body">
          您应以商业主体的形式（包括但不限于有限责任公司、股份有限公司、个体工商户等）在美稻AI平台从事商业行为，您及该等商业主体并授权美稻AI平台代为申请商业主体的电子印章、进行电子签约等。
        </div>
      </scroll-view>
      <div :style="keepBottomSafeDis()" class="flex_cen_cen mt20">
        <div :class="isAllRead ? 'btn_primary_1_light' : 'btn_primary_1_dark'" @tap="readFn">我已全部阅读并同意以上合作须知内容</div>
      </div>
    </div>
  </Drawer>
  <!-- 法大大手机号验证 -->
  <Popup ref="faDaDaRef">
    <div class="popup_cen">
      <div class="popup_title">
        手机号验证
        <div class="icon_close" @tap="closeMobileValidateFn">
          <Icon name="icon-shanchu-4" size="28" />
        </div>
      </div>
      <div class="popup_name mt48">请填写手机号：</div>
      <div class="mobile_tip">{{ phoneDesensitize(mobile) }} 收到的短信验证码</div>
      <div class="code_box">
        <VCode ref="vCodeRef" @code="form.verifyCode = $event" />
      </div>
      <div
        :style="{color: codeTime === 30 ? '#ff8002' : 'rgba(0, 0, 0, 0.45)'}"
        class="code_get"
        @tap="getVCdoe"
      >
        {{ getVCodeBtn }}
      </div>
    </div>
  </Popup>
  <!-- 提示信息太长的使用此弹窗 -->
  <Popup ref="popupRef">
    <Pconfirm :confirm-text="popupInfo.confirmText" :is-two-btn="false" :tip-text="popupInfo.tipText" tip-title="提示" @confirm="popupRef.change()" />
  </Popup>
  <!-- 被驳回，提交时资料没有修改时提示 -->
  <u-popup :close-on-click-overlay="false" :show="showConfirmSubmitPopup" bg-color="transparent" mode="center" overlay-opacity="0.25">
    <Pconfirm tip-text="您的资料未修改，确认提交吗？" tip-title="提示" @cancel="showConfirmSubmitPopup = false" @confirm="confirmSubmitFn" />
  </u-popup>
</template>

<script lang="ts" setup>
import LabelAndValue from '@C/LabelAndValue.vue'
import Input from '@C/Input.vue'
import { computed, reactive, ref, watch } from 'vue'
import RadioSelect from '@C/RadioSelect.vue'
import Drawer from '@C/Drawer.vue'
import SiteSelect from '@C/SiteSelect.vue'
import Button from '@C/Button.vue'
import Image from '@C/Image.vue'
import Confirm from '@C/Confirm.vue'
import { Msg, MsgLoading, MsgLoadingClear } from '@C/Msg'
import {
  onLoad,
  Router,
  storeState,
  checkIDNoFormat,
  keepBottomSafeDis,
  phoneDesensitize,
  checkEmailFn,
  onUnload,
} from '@U/common'
import { clearToken, loginOK } from '@U/Auth'
import Popup from '@C/Popup.vue'
import {
  getPersonAccountDefAuth,
  ocr_idCardBack,
  ocr_idCardFront,
  ocr_gangAoTaiPassFront, getRegCode,
} from '@P/Auth/request'
import DateSelect from '@C/DateSelect.vue'
import Pconfirm from '@C/Pconfirm.vue'
import Icon from '@C/Icon.vue'
import StateSelect from '@C/StateSelect.vue'
import dayjs from 'dayjs'
import VCode from '@C/VCodeKeyBoard.vue'
import { type IObj, hasVarNumber } from '@/interface'
import { saveZhiKeRegInfo } from './request'

const idTypeEnum = [
  { label: '身份证', value: '5001' },
  { label: '港澳来往内地通行证（回乡证）', value: '5002' },
  { label: '台湾来往大陆通行证（台胞证）', value: '5003' },
]
const idTypeRef = ref({})
const cardTypeName = ref('')
const idTypeConfirmFn = (val: string, valObj: IObj) => {
  idTypeRef.value.change()
  cardTypeName.value = valObj.label
  form.CardType = val
  // 确认切换证件类型后清空之前的信息
  form.CardImgBack = ''
  form.CardImgFront = ''
  form.Name = ''
  form.Sex = ''
  form.CardNo = ''
  // form.IsLongterm = false
  form.CardExpdate = ''
}
const idCardTitle = computed(() => {
  if (form.CardType === '5001') return { name: '身份证件', idCardFrontTip: '上传身份证-人像面', idCardBackTip: '上传身份证-国徽面', cardDefaultPersonImg: 'id_card_front', cardDefaultImgFront: 'id_card_back', maxLength: '18' }
  if (form.CardType === '5002') return { name: '港澳居民来往内地通行证（回乡证）', idCardFrontTip: '港澳居民来往内地通行证-正面', idCardBackTip: '港澳居民来往内地通行证-背面', cardDefaultPersonImg: 'hk_macao_pass_front', cardDefaultImgFront: 'hk_macao_pass_back', maxLength: '11' }
  if (form.CardType === '5003') return { name: '台湾居民来往大陆通行证（台胞证）', idCardFrontTip: '台湾居民来往大陆通行证-正面', idCardBackTip: '台湾居民来往大陆通行证-背面', cardDefaultPersonImg: 'taiwan_pass_front', cardDefaultImgFront: 'taiwan_pass_back', maxLength: '8' }
})
const toIDViewFn = (side: string) => {
  Router.push('ID_Viewfinder', { side, cardType: form.CardType })
}

const CPM_Mobile = ref('')
// 根据智客手机号判断属于哪个运营商
const chinaMobile = ['134', '135', '136', '137', '138', '139', '147', '148', '150', '151', '152', '157', '158', '159', '172', '178', '182', '183', '184', '187', '188', '195', '197', '198'] // 中国移动
const chinaTelecom = ['133', '141', '149', '153', '173', '174', '177', '180', '181', '189', '190', '191', '193', '199'] // 中国电信
const chinaTelecomSpecial = '1349' // 中国电信特殊
const chinaUnicom = ['130', '131', '132', '140', '145', '146', '155', '156', '166', '175', '176', '185', '186', '196'] // 中国联通
const checkPhoneOperator = () => {
  const theFirstThree = storeState.loginForm?.username?.substring(0, 3)
  const theFirstFour = storeState.loginForm?.username?.substring(0, 4)
  if (storeState.loginForm?.username) {
    if (chinaMobile.includes(theFirstThree)) form.Email = `${storeState.loginForm?.username}@139.com`
    if (chinaTelecom.includes(theFirstThree) || chinaTelecomSpecial === theFirstFour) form.Email = `${storeState.loginForm?.username}@189.cn`
    if (chinaUnicom.includes(theFirstThree)) form.Email = `${storeState.loginForm?.username}@wo.cn`
  }
}
// onLoad 生命周期函数 只在路由历史记录中第一次进入该页面时调用，从下一个页面返回时不会调用
onLoad(() => {
  getDefForm()
  uni.$once('getDefForm', getDefForm)
})

// 组件样式
const labelValueStyle = { 'borderBottom': '1rpx solid rgba(0,0,0,0.1)', 'width': '628rpx', 'height': '86rpx', 'marginTop': '28rpx', paddingLeft: 0, paddingRight: 0 }

// 提交表单
const form = reactive({
  Name: '',
  Sex: '',
  Email: '',
  Province: '',
  City: '',
  District: '',
  ProvinceCode: '',
  CityCode: '',
  DistrictCode: '',
  Address: '',
  CardImgFront: '',
  CardImgBack: '',
  CardNo: '',
  CardExpdate: '',
  // IsLongterm: false,
  CardType: '5001',
  verifyCode: '',
  // 身份证住址
  IDAddress: '',
})

const closeCooperateNotice = () => {
  cooperateNoticeRef.value.change()
}

watch(
    () => storeState.routeParams,
    (newVal) => {
      if (newVal._path) {
        if (newVal.IDSide === 'IDPersonImg') form.CardImgBack = newVal._path
        else form.CardImgFront = newVal._path
      }
    },
)
// OCR
watch(
    () => form.CardImgFront,
    async (newVal: string) => {
      if (newVal) {
        await MsgLoading('识别中')
        if (form.CardType === '5001') {
          const res = await ocr_idCardFront({ imgPath: newVal }).finally(() => MsgLoadingClear())
          if (res?.data) {
            const { cardExpdate, cardIssuedDate } = res.data
            form.CardExpdate = `${cardIssuedDate}-${cardExpdate}`
          } else form.CardExpdate = ''
        }
      }
    },
)
watch(
    () => form.CardImgBack,
    async (newVal: string) => {
      if (newVal) {
        await MsgLoading('识别中')
        let res = {}
        if (form.CardType === '5001') {
          res = await ocr_idCardBack({ imgPath: newVal }).finally(() => MsgLoadingClear())
          const { sex } = res.data
          form.Sex = sex === '男' ? '0' : '1'
        } else {
          res = await ocr_gangAoTaiPassFront({ imgPath: newVal, cardType: form.CardType }).finally(() => MsgLoadingClear())
          const { sex, cardExpdate } = res.data
          if (sex === '男') form.Sex = '0'
          else if (sex === '女') form.Sex = '1'
          else form.Sex = ''
          const startDate = cardExpdate.split('-')[0]
          const endDate = cardExpdate.split('-')[1]
          // 符合YYYY.MM.DD格式才赋值
          if (dayjs(startDate, 'YYYY.MM.DD').isValid() && dayjs(endDate, 'YYYY.MM.DD').isValid()) {
            form.CardExpdate = `${dayjs(startDate).format('YYYY-MM-DD') }-${ dayjs(endDate).format('YYYY-MM-DD')}`
          } else form.CardExpdate = ''
        }
        const { trueName, cardNo, address } = res.data
        form.CardNo = cardNo
        form.Name = trueName
        form.IDAddress = address
      }
    },
)

// 已填写
const CheckRef = ref()
const changeCheckShow = () => { CheckRef.value?.change() }
const formStatus = ref(0) // 0待填写 1待审核 2审核通过 3驳回
const rejectReason = ref('')
// 获取默认资料
let feedbackOldData = {}
async function getDefForm() {
  await MsgLoading()
  const { data } = await getPersonAccountDefAuth().finally(() => { MsgLoadingClear() })
  if (data && Object.keys(data).length) {
    form.Name = data?.name || ''
    form.Sex = hasVarNumber(data.sex) ? data.sex.toString() : ''
    form.Email = data?.email || ''
    form.Province = data?.province || ''
    form.City = data?.city || ''
    form.District = data?.district || ''
    form.ProvinceCode = data?.provinceCode || ''
    form.CityCode = data?.cityCode || ''
    form.DistrictCode = data?.districtCode || ''
    form.Address = data?.address || ''
    form.CardImgFront = data?.cardImgFront || ''
    form.CardImgBack = data?.cardImgBack || ''
    form.CardNo = data?.cardNo || ''
    form.CardExpdate = data?.idValidity
    form.IDAddress = data?.idAddress || ''
    // form.IsLongterm = data?.longTimeOrNo || false

    formStatus.value = data?.profileStatus
    rejectReason.value = data?.rejectReason
    feedbackOldData = JSON.parse(JSON.stringify(form))
    switch (formStatus.value) {
      case 1: return Router.push('accountReview')
      case 2: {
        // await partner_getAccountInfo()
        return loginOK()
      }
      case 3: return changeCheckShow()
    }
    // 如果回显接口没有邮箱地址，则设置默认值
    if (!data?.email) {
      checkPhoneOperator()
    }
  }
}

// 选择省市区
const siteRef = ref()
const selectSite = () => {
  siteRef.value.change()
}
const setSite = (e: IObj) => {
  form.Province = e?.province.name
  form.City = e?.city.name
  form.District = e?.district.name
  form.ProvinceCode = e?.province.code
  form.CityCode = e?.city.code
  form.DistrictCode = e?.district.code
  siteRef.value.change()
}
const cancelSite = () => { siteRef.value.change() }
// 显示文本
const siteText = computed(() => (form.District ? `${form.Province}/${form.City}/${form.District}` : '<span style="color: rgb(0, 0, 0, 0.25)">请选择常驻地区</span>'))
// 省市区默认选择项
const defSite = computed(() => ({
  province: { name: form.Province, code: form.ProvinceCode },
  city: { name: form.City, code: form.CityCode },
  district: { name: form.District, code: form.DistrictCode },
}))

// 证件有效期显示文本
// const cardText = computed(() => (form.IsLongterm ? `${form.CardExpdate.slice(0, 10)}--长期有效` : form.CardExpdate.slice(0, 21) || '未获取'))
const cardText = computed(() => (form.CardExpdate.slice(0, 21) || '未获取'))

// 身份证日期选择
const DateRef = ref()
// 打开日期弹框
// const openDateDrewer = () => { DateRef.value.change() }
const DateChange = (date: string[]) => {
  let CardExpdate = ''
  date.forEach((i: string) => { CardExpdate += `${i}-` })
  form.CardExpdate = CardExpdate.substring(0, 21)
  DateRef.value.change()
}
const cancelDate = () => { DateRef.value.change() }

// const Swictch = (value:boolean) => {
//   if (!form.CardExpdate) {
//     Msg({ msg: '请选择身份证开始时间' })
//     form.IsLongterm = false
//     return false
//   }
//   form.IsLongterm = value
// }

// 身份证已被使用弹框
const cardNoRef = ref()

// 重新登录
const logInAgain = () => {
  clearToken()
  setTimeout(() => Router.reLaunch('login'), 1000)
  cardNoRef.value?.change()
}

const iKnow = () => {
  cardNoRef.value?.change()
}
// 合作须知
const cooperateNoticeRef = ref()
const isAllRead = ref(false)
const selectFn = () => {
  if (!isAllRead.value) cooperateNoticeRef.value.change()
}
const readFn = () => {
  if (isAllRead.value) cooperateNoticeRef.value.change()
}
const faDaDaRef = ref()
const getVCdoe = async () => {
  if (codeTime.value === 30) {
    codeTimer.value = setInterval(() => {
      --codeTime.value
      if (codeTime.value < 1) {
        codeTime.value = 30
        clearInterval(codeTimer.value)
      }
    }, 1000)
    const { code } = await getRegCode().finally(() => {})
    if (code === 200) {
      Msg({ icon: 'success', msg: '已发送' })
    } else {
      clearInterval(codeTimer.value)
      codeTime.value = 30
      Msg({ icon: 'error', msg: '发送失败' })
    }
  }
}
// 验证码倒计时
const codeTime = ref(29)
const codeTimer = ref()
// 获取验证码
const getVCodeBtn = computed(() => `${codeTime.value !== 30 ? `${codeTime.value}s 后可重新获取` : '获取验证码'}`)
const closeMobileValidateFn = () => {
  codeTime.value = 29
  clearInterval(codeTimer.value)
  faDaDaRef.value.change()
}
const openMobileValidateBox = async () => {
  await MsgLoading()
  const res = await getRegCode().finally(() => { MsgLoadingClear() })
  if (res?.code === 200) {
    faDaDaRef.value.change()
    codeTimer.value = setInterval(() => {
      --codeTime.value
      if (codeTime.value < 1) {
        codeTime.value = 30
        clearInterval(codeTimer.value)
      }
    }, 1000)
    Msg({ icon: 'success', msg: '已发送' })
  }
}
const mobile = computed(() => storeState.zhiKeInfo.mobile)
const num = ref(0)
watch(
    () => form.verifyCode,
    () => {
      if (form.verifyCode.length === 6) {
        num.value += 1
        if (num.value === 1) {
          num.value = 0
          submitAbout()
          // clearInterval(codeTimer.value)
          // faDaDaRef.value.change()
        }
      }
    },
)
const popupRef = ref()
const vCodeRef = ref()
const popupInfo = reactive({
  tipText: '',
  confirmText: '',
})
let authenticationFailCount = 0
const submitAbout = async () => {
  await MsgLoading()
  const { code, msg } = await saveZhiKeRegInfo(form).finally(() => {
    vCodeRef.value.init()
    form.verifyCode = ''
  })
  if (code === 200) {
    uni.hideLoading()
    Router.push('accountReview')
    faDaDaRef.value.change()
  }
  if (code === 203) faDaDaRef.value.change()
  if (code === 212) {
    uni.hideLoading()
    if (msg.includes('短信验证码不匹配')) return Msg({ msg: '短信验证码错误，请重新填写', duration: 3000 })
    if (msg.includes('短信验证码失效')) return Msg({ msg: '短信验证码已失效，请重新获取', duration: 3000 })
    faDaDaRef.value.change()
    if (msg.includes('实名认证')) {
      feedbackOldData = JSON.parse(JSON.stringify(form))
      authenticationFailCount += 1
    }
    if (authenticationFailCount > 3) {
      popupInfo.tipText = '您的实名错误次数太多，可以联系客服协助处理哦～'
      popupInfo.confirmText = '我知道了'
      return popupRef.value.change()
    }
    popupInfo.confirmText = '去修改'
    popupInfo.tipText = msg
    popupRef.value.change()
  }
}
// 提交
const showConfirmSubmitPopup = ref(false)
const submit = () => {
  if (!form.CardImgBack) {
    if (form.CardType === '5001') return Msg({ msg: '请上传身份证人像面' })
    if (form.CardType === '5002') return Msg({ msg: '请上传回乡证正面' })
    if (form.CardType === '5003') return Msg({ msg: '请上传台胞证正面' })
  }
  if (!form.CardImgFront) {
    if (form.CardType === '5001') return Msg({ msg: '请上传身份证国徽面' })
    if (form.CardType === '5002') return Msg({ msg: '请上传回乡证背面' })
    if (form.CardType === '5003') return Msg({ msg: '请上传台胞证背面' })
  }
  if (!form.Name) return Msg({ msg: '请输入姓名' })
  if (!form.Sex) return Msg({ msg: '请选择性别' })
  if (!form.CardNo) return Msg({ msg: '请输入证件号码!' })
  if (form.CardType === '5001') {
    const resInfo = checkIDNoFormat('idCard', form.CardNo)
    if (!resInfo.pass) return Msg({ msg: resInfo.msg })
  }
  if (form.CardType === '5002') {
    const resInfo = checkIDNoFormat('gangAoPass', form.CardNo)
    if (!resInfo.pass) return Msg({ msg: resInfo.msg })
  }
  if (form.CardType === '5003') {
    const resInfo = checkIDNoFormat('taiwanPass', form.CardNo)
    if (!resInfo.pass) return Msg({ msg: resInfo.msg })
  }
  if (!form.CardExpdate) return Msg({ msg: '请输入证件有效期' })
  // if (form.IsLongterm) {
  //   form.CardExpdate = form.CardExpdate.substring(0, 10)
  // }
  if (!(form.Province && form.City && form.District)) return Msg({ msg: '请选择常驻地区' })
  if (!form.Address) return Msg({ msg: '请输入常驻地区详细地址' })
  if (!form.Email) return Msg({ msg: '请输入电子邮箱' })
  if (!checkEmailFn(form.Email)) return Msg({ msg: '电子邮箱格式不正确' })
  if (!isAllRead.value) return Msg({ msg: '请先阅读并同意合作须知' })
  // 判断资料被驳回时用户是否有修改资料
  if (formStatus.value === 3) {
    let isHasOneDifferent = false
    for (const key in feedbackOldData) {
      if (feedbackOldData[key] !== form[key]) {
        isHasOneDifferent = true
        break // 满足条件跳出整个循环
      }
    }
    if (!isHasOneDifferent) {
      showConfirmSubmitPopup.value = true
      return false
    }
  }
  openMobileValidateBox()
  // if (code === 203) {
  //   CPM_Mobile.value = msg
  //   cardNoRef.value?.change()
  // }
}
const confirmSubmitFn = () => {
  openMobileValidateBox()
  showConfirmSubmitPopup.value = false
}
onUnload(() => {
  if (codeTimer.value) clearInterval(codeTimer.value)
})
</script>

<style lang="less" scoped>
.wrap {
  .reject_tip {
    position: fixed;
    left: 0;
    top: 0;
    padding: 10rpx 20rpx;
    font-size: 32rpx;
    color: #595959;
    background: #fff2e5;
    z-index: 9999;
  }
  //基本资料
  .box_info {
    background: #FFFFFF;
    padding: 30rpx 45rpx;
    box-sizing: border-box;
    .title {
      width: 294rpx;
      height: 66rpx;
      font-size: 48rpx;
      font-weight: 400;
      color: rgba(0,0,0,0.85);
      line-height: 66rpx;
      //margin: 0 40rpx 20rpx 30rpx;
      margin: 0 40rpx 20rpx 0;
    }
    .title_1 {
      height: 34rpx;
      font-weight: 400;
      font-size: 28rpx;
      color: rgba(0,0,0,0.45);
      //margin: 0 0 50rpx 30rpx;
    }
    .select {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      font-size: 28rpx;
      line-height: 86rpx;
      text-align: right;
      opacity: 0.85;
    }
    .identity {
      //margin-left: 30rpx;
      //width: 164rpx;
      height: 44rpx;
      font-size: 32rpx;
      font-weight: 550;
      color: rgba(0,0,0,0.85);
      line-height: 44rpx;
      margin-top: 28rpx;
    }
  }
  //身份证件
  .date {
    height:800rpx;
    background: #FFFFFF;
    padding: 20rpx 62rpx 0 45rpx;
    box-sizing: border-box;
  }
  .box_card {
    margin-top: 20rpx;
    background: #FFFFFF;
    padding: 30rpx 45rpx;
    box-sizing: border-box;
    .identity {
      //margin-left: 30rpx;
      width: 164rpx;
      height: 44rpx;
      font-size: 32rpx;
      font-weight: 550;
      color: rgba(0,0,0,0.85);
      line-height: 44rpx;
    }
    .btn {
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 60rpx 0 20rpx;
    }
    .read_tip {
      font-weight: 400;
      font-size: 28rpx;
      color: rgba(0,0,0,0.45);
      line-height: 40rpx;
    }
  }
  .card_no {
    font-size: 28rpx;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    ._placeholder {
      padding-left: 16rpx;
    }

  }
  .card_no_switch{
    font-size: 28rpx;
    display: flex;
    align-items: center;
    justify-content:flex-end;
    margin: 20rpx 15rpx;
    .switch_content {
      width: 112rpx;
      height: 44rpx;
      font-weight: 400;
      color: rgba(0,0,0,0.65);
      line-height: 44rpx;
      margin: 0 20rpx;
    }
  }
  .tips {
    text-align: left;
  }
  .touch_area {
    width: 36rpx;
    height: 56rpx;
    .meidao-switch-more {
      width: 28rpx;
      height: 28rpx;
      border: 2rpx solid;
      display: flex;
      justify-content: center;
      align-items: center;
      transition: all .3s;
      border-radius: 8rpx;
    }
  }
}
.popup_box {
  .content {
    font-weight: 400;
    font-size: 32rpx;
    color: #202021;
    line-height: 80rpx;
    margin-top: 40rpx;
  }
}
.popup_cen {
  .mobile_tip {
    font-weight: 400;
    font-size: 28rpx;
    color: rgba(0,0,0,0.45);
    line-height: 40rpx;
    margin-bottom: 84rpx;
  }
  .code_box {
    height: 85rpx;
    margin-bottom: 46rpx;
  }
  .code_get {
    height: 34rpx;
    color: rgba(0, 0, 0, 0.45);
    font-size: 24rpx;
  }
}
</style>
